<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Inspection extends CI_Controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->database();
		$this->load->helper('url');

		$this->load->library('grocery_CRUD');
	}
	public function _example_output($output = null)
	{
		$this->load->view('master/grid',$output);
	}
	public function request()
	{
		$this->load->vars('title','Request For Inspection');

		$crud = new grocery_CRUD();
		
		$crud->columns('no_srt','tgl_srt','to_attn','from_attn','subject');
		$crud->set_theme('flexigrid');
		$this->config->load('grocery_crud');
		//$this->config->set_item('grocery_crud_dialog_forms',false);
		$crud->set_table('request_for_inspection');
		$crud->set_subject('Request For Inspection');
		$crud->unset_export();
		$crud->unset_print();
		$crud->field_type('to_address','text');
		$crud->unset_texteditor('to_address');
		$crud->field_type('from_address','text');
		$crud->unset_texteditor('from_address');
		$crud->field_type('exporter_address','text');
		$crud->unset_texteditor('exporter_address');
		$crud->field_type('importer_address','text');
		$crud->unset_texteditor('importer_address');
		$crud->field_type('company_address','text');
		$crud->unset_texteditor('company_address');
		///
		$crud->set_relation('id_afiliasi','cabang','nama');

		$crud->display_as('no_srt','Nomor Surat');
		$crud->display_as('tgl_surat','Tanggal Surat');
		$crud->display_as('id_afiliasi','Cabang Afiliasi');
		$crud->display_as('to_attn','Attn');
		$crud->display_as('to_address','Address');
		$crud->display_as('to_telp','Tel.');
		$crud->display_as('to_fax','Fax.');
		$crud->display_as('to_email','Email');
		$crud->display_as('from_attn','Attn');
		$crud->display_as('from_address','Address');
		$crud->display_as('from_telp','Tel.');
		$crud->display_as('from_fax','Fax.');
		$crud->display_as('from_email','Email');
		$crud->display_as('name','Nama');
		$crud->display_as('subject_oi','Subject Of Inspection');
		$crud->display_as('description_og','Description Of Good');
		$crud->display_as('importer','Company Name');
		$crud->display_as('importer_attn','Attn');
		$crud->display_as('importer_address','Address');
		$crud->display_as('importer_telp','Tel.');
		$crud->display_as('importer_fax','Fax.');
		$crud->display_as('importer_email','Email');

		$crud->display_as('exporter','Company Name');
		$crud->display_as('exporter_attn','Attn');
		$crud->display_as('exporter_address','Address');
		$crud->display_as('exporter_telp','Tel.');
		$crud->display_as('exporter_fax','Fax.');
		$crud->display_as('exporter_email','Email');

		$crud->display_as('place_io','Place Of Inspection');
		$crud->display_as('date_oi','Date Of Inspection');
		$crud->display_as('company_name','Nama');
		$crud->display_as('company_npwp','NPWP');
		$crud->display_as('company_address','Alamat');
		$crud->display_as('applicants_name',"Applicant's Name");


		$crud->callback_add_field('subject_oi',array($this,'_cb_subject_io'));
		$crud->callback_edit_field('subject_oi',array($this,'_cb_subject_io'));
		$crud->callback_add_field('description_og',array($this,'_cb_description_og'));
		$crud->callback_edit_field('description_og',array($this,'_cb_description_og'));
		
		$crud->unset_read();
		$crud->add_action('', 'detail', 'inspection/pdf/rfi','ui-icon ui-icon-disk rfi_pdf_cmd');

		$output = $crud->render();

		$this->_example_output($output);
	}
	public function _cb_subject_io($val,$id)
	{
		return '<div id="subject_oi_field_box"> <div id="field-subject_oi"> <input type="radio" name="subject_oi" value="1" '.($val=='1'?' checked' : '').' />  Second Hand Good    <input type="radio" name="subject_oi" value="2" '.($val=='2'?' checked' : '').'/> Others</div></div>';
	}
	public function _cb_description_og($val,$id)
	{
		return '<div id="description_og_field_box"> <div id="field-description_og" style="width:400px !important"><input type="radio" name="description_og" value="1" '.($val=='1'?' checked' : '').' />  Machine/Heavy Equipment    <input type="radio" name="description_og" value="2" '.($val=='2'?' checked' : '').'/> Others</div></div>';
	}
	public function order()
	{
		$this->load->vars('title','Inspection Order');

		$crud = new grocery_CRUD();
		
		$crud->set_theme('flexigrid');
		$this->config->load('grocery_crud');
		//$this->config->set_item('grocery_crud_dialog_forms',false);
		$crud->set_table('inspection_order');
		$crud->set_subject('Inspection Order');
		// $crud->unset_fields('userpassword');
		// $crud->unset_columns('userpassword');
		//$crud->field_type('attachment','true_false');
		//$crud->display_as('attachment','Attach');

		//$crud->display_as('name','Keterangan');
		//$crud->display_as('ordering','No. Urut');
		//$crud->field_type('name','text');
		//$crud->unset_texteditor('name');
		$crud->unset_export();
		$crud->unset_print();
		// $crud->set_relation('id_cabang','cabang','nama');
		// $crud->display_as('id_cabang','Cabang');
		//$output->title = ;
		$crud->columns('io_no','io_from_date','io_to','io_address');
		$crud->display_as('io_no','Nomor');
		$crud->display_as('io_from_date','Tanggal');
		$crud->display_as('io_to','Kepada');
		$crud->display_as('io_address','Alamat');
		$crud->display_as('io_doc_type','Jenis Dokumen');
		$crud->display_as('no_packing_list','No Packing List');
		$crud->display_as('id_afiliasi','Cabang Afiliasi');

		// 

		$crud->display_as('io_from_name','Nama');
		$crud->display_as('io_from_tel','Tel');
		$crud->display_as('io_from_fax','Fax');
		$crud->display_as('io_from_email','Email');
		$crud->display_as('io_from_attn','Attn');
		// 

		$crud->display_as('io_to','Nama');
		$crud->display_as('io_attn','Attn');
		$crud->display_as('io_address','Alamat');
		$crud->display_as('io_tel_no','Tel');
		$crud->display_as('io_fax_no','Fax');
		$crud->display_as('io_email','Email');

		$crud->display_as('io_contact_name','Nama');
		$crud->display_as('io_contact_mobile','Mobile');
		$crud->display_as('io_contact_tel','Telepon');
		$crud->display_as('io_contact_fax','Fax');
		$crud->display_as('io_contact_email','Email');
		$crud->display_as('io_remarks','Catatan');
		$crud->display_as('io_signature_name','Tertanda');
		//
		$crud->display_as('io_services','Service');
		$crud->add_fields("io_no", "io_from_date", "io_doc_type", "no_packing_list", "io_from_name", "io_from_tel", "io_from_fax", "io_from_email", "io_from_attn", "io_to", "io_address", "io_attn", "io_tel_no", "io_fax_no", "io_email", "Importir", "Alamat_Importir", "Telp_Importir", "Fax_Importir", "Eksportir", "Alamat_Eksportir", "Telp_Eksportir", "Fax_Eksportir", "Alamat_Pemeriksaan", "Tanggal_Periksa", "io_services",'io_contact_name','io_contact_mobile','io_contact_tel','io_contact_fax','io_contact_email','io_remarks','io_signature_name');
		$crud->edit_fields("io_no", "io_from_date", "io_doc_type", "no_packing_list", "io_from_name", "io_from_tel", "io_from_fax", "io_from_email", "io_from_attn", "io_to", "io_address", "io_attn", "io_tel_no", "io_fax_no", "io_email", "Importir", "Alamat_Importir", "Telp_Importir", "Fax_Importir", "Eksportir", "Alamat_Eksportir", "Telp_Eksportir", "Fax_Eksportir", "Alamat_Pemeriksaan", "Tanggal_Periksa", "io_services",'io_contact_name','io_contact_mobile','io_contact_tel','io_contact_fax','io_contact_email','io_remarks','io_signature_name');

		$crud->unset_texteditor('io_remarks');
		$crud->field_type('id','hidden');
		$crud->callback_add_field('io_services',array($this,'_cb_io_services'));
		$crud->callback_edit_field('io_services',array($this,'_cb_io_services'));
		$crud->callback_after_insert(array($this, '_add_io_scope_of_work'));
		$crud->callback_after_update(array($this, '_edit_io_scope_of_work'));
		$crud->unset_read();

		$crud->add_action('', 'detail', 'inspection/pdf/io','ui-icon ui-icon-disk io_pdf_cmd');

		$output = $crud->render();

		$this->_example_output($output);
	}
	public function _cb_io_services($val,$id)
	{
		//print_r(func_get_args());
		
		return ' <input type="radio" name="io_services" value="1" '.($val=='1'?' checked' : '').' />  Second Hand Goods Inspection  <input type="radio" name="io_services" value="2" '.($val=='2'?' checked' : '').'/> Others';
	}
	public function scope()
	{
		$this->load->vars('title','Inspection / IO Scope of Work');

		$crud = new grocery_CRUD();
		
		$crud->set_theme('flexigrid');
		$this->config->load('grocery_crud');
		$crud->set_table('io_scope_of_work');
		$crud->set_subject('IO Scope of Work');
		// $crud->unset_fields('userpassword');
		// $crud->unset_columns('userpassword');
		$crud->field_type('attachment','true_false');
		$crud->display_as('attachment','Attach');

		$crud->display_as('name','Keterangan');
		$crud->display_as('ordering','No. Urut');
		$crud->field_type('name','text');
		$crud->unset_texteditor('name');


		$crud->unset_export();
		$crud->unset_print();

		
		// $crud->set_relation('id_cabang','cabang','nama');
		// $crud->display_as('id_cabang','Cabang');
		//$output->title = ;
		$output = $crud->render();

		$this->_example_output($output);
	}
	public function _edit_io_scope_of_work($post,$id)
	{
		$io_scope_of_work = json_decode($post['io_scope_of_work']);
		foreach ($io_scope_of_work as $scope_id => $value ) {
			$this->db->where('id',$scope_id)->update('io_scope_of_work_ceklist',array('value'=>$value));
		}
	}
	public function _add_io_scope_of_work($post,$id)
	{
		$io_scope_of_work = json_decode($post['io_scope_of_work']);
		foreach ($io_scope_of_work as $scope_id => $value ) {
			$this->db->insert('io_scope_of_work_ceklist',array('io_id'=>$id,'io_scope_of_work_id'=>$scope_id,'value'=>$value));
		}
	}
	public function from_config()
	{
		$config = $this->db->select('kop_from,kop_tel,kop_fax,kop_email,rekening_nama')->get('config')->row();
		echo json_encode($config);
	}
	public function scope_ceklist($io_id)
	{
		//echo $io_id;
		// GET SCOPE OF WORK

		if( $io_id == 'insert')
		{
			$io_scope_of_work = $this->db->order_by('ordering')->get('io_scope_of_work')->result_object();
			$scope_count = count($io_scope_of_work);
			$data = '<div class="form-display-as-box">Scope of Work</div>';
			$data .= '<div class="form-input-box">';
			foreach ($io_scope_of_work as $ceklist) {
				$data .= '<div class="scope"><input class="set" type="checkbox" rowid="'.$ceklist->id.'" '. ($ceklist->attachment == '1' ? ' checked="checked" ':' '). '/> <label>'.$ceklist->name.'</label></div>';
			}
			$data .= '</div><input type="hidden" name="io_scope_of_work"/><div class="clear"></div>';
			//print_r($data);
			echo $data;
			die();
		}
		$io = $this->db->where('id',$io_id)->get('inspection_order')->row();
		if(!empty($io))
		{
			$io_scope_of_work = $this->db->order_by('ordering')->get('io_scope_of_work')->result_object();
			$scope_count = count($io_scope_of_work);

			$io_scope_of_work_ceklist = $this->db->select('a.id,a.value,b.name,b.id as scope_id')
													 ->where('a.io_id',$io_id)
													 ->from('io_scope_of_work_ceklist a')
													 ->join('io_scope_of_work b','a.io_scope_of_work_id = b.id')
													 ->get()->result_object();
			//										 
			$ceklist_count = count($io_scope_of_work_ceklist);
			
			//die();
			//echo $ceklist_count;
			if($scope_count != $ceklist_count)
			{
				//echo 'You Are Here';
				//$io_scope_of_work_ceklist = array();
				//$this->db->where('io_id',$io_id)->delete('io_scope_of_work_ceklist');
				// GET ID SCOPE OF WORK FOR CHECKING UNEXISTENT
				$must_exists = array();
				$already_exists = array();
				foreach ($io_scope_of_work as $scope_of_work) {
					$must_exists[] = $scope_of_work->id;

				}
				foreach ($io_scope_of_work_ceklist as $ceklist ) {
					$already_exists[]=$ceklist->scope_id;
				}	
				$unexistent = array_diff($must_exists, $already_exists);
				
				//print_r($unexistent);
				//die();
				if(count($unexistent) > 0)
				{
					foreach ($unexistent as $scope_id) {
						$ceklist = array(
							'io_id'	=> $io_id,
							'io_scope_of_work_id' => $scope_id,
							'value' => ''	
						);
						$this->db->insert('io_scope_of_work_ceklist',$ceklist);
					}
					
				}

					
				// AMBIL KEMBALI
				$io_scope_of_work_ceklist = $this->db->select('a.id,a.value,b.name')
													 ->where('a.io_id',$io_id)
													 ->from('io_scope_of_work_ceklist a')
													 ->join('io_scope_of_work b','a.io_scope_of_work_id = b.id')
													 ->get()->result_object();
				$ceklist_count = count($io_scope_of_work_ceklist);
			}
		//	$data  = '<div class="form-field-box even io-scope-of-work">';
			$data = '<div class="form-display-as-box">Scope of Work</div>';
			$data .= '<div class="form-input-box">';
			foreach ($io_scope_of_work_ceklist as $ceklist) {
				$data .= '<div class="scope"><input class="set" type="checkbox" rowid="'.$ceklist->id.'" '. ($ceklist->value == '1' ? ' checked="checked" ':' '). '/> <label>'.$ceklist->name.'</label></div>';
			}
			$data .= '</div><input type="hidden" name="io_scope_of_work"/><div class="clear"></div>';
			//print_r($data);
			echo $data;
		}
		// GENERATE OR WHERE


	}

	public function pdf($what,$id)
	{
		if( !in_array($what, array('rfi','io')) || !$id )
			die('Invalid Parameter');
		$tbl = array(
			'rfi' => 'request_for_inspection',
			'io' => 'inspection_order'
		);
		$ql = $this->db->where('id',$id)->get($tbl[$what])->row();
		$config = $this->db->get('config')->row();
		if($ql){
			//// PDF STAERTED
			// As PDF creation takes a bit of memory, we're saving the created file in /downloads/reports/
			$filename = $tbl[$what] . '-'.$id;
			$pdfFilePath = FCPATH."/dl/pdfs/$filename.pdf";

			//die($pdfFilePath);
			$data['page_title'] = 'Hello world'; // pass data to the view
			$data['ql'] = $ql; 
			$data['config'] = $config;
			if($what == 'io'){

				/*BEGIN*/
				if(!empty($ql))
				{
					$io_id = $id;
					$io_scope_of_work = $this->db->order_by('ordering')->get('io_scope_of_work')->result_object();
					$scope_count = count($io_scope_of_work);

					$io_scope_of_work_ceklist = $this->db->select('a.id,a.value,b.name,b.id as scope_id')
															 ->where('a.io_id',$io_id)
															 ->from('io_scope_of_work_ceklist a')
															 ->join('io_scope_of_work b','a.io_scope_of_work_id = b.id')
															 ->get()->result_object();
					//										 
					$ceklist_count = count($io_scope_of_work_ceklist);
					
					//die();
					//echo $ceklist_count;
					if($scope_count != $ceklist_count)
					{
						//echo 'You Are Here';
						//$io_scope_of_work_ceklist = array();
						//$this->db->where('io_id',$io_id)->delete('io_scope_of_work_ceklist');
						// GET ID SCOPE OF WORK FOR CHECKING UNEXISTENT
						$must_exists = array();
						$already_exists = array();
						foreach ($io_scope_of_work as $scope_of_work) {
							$must_exists[] = $scope_of_work->id;

						}
						foreach ($io_scope_of_work_ceklist as $ceklist ) {
							$already_exists[]=$ceklist->scope_id;
						}	
						$unexistent = array_diff($must_exists, $already_exists);
						
						//print_r($unexistent);
						//die();
						if(count($unexistent) > 0)
						{
							foreach ($unexistent as $scope_id) {
								$ceklist = array(
									'io_id'	=> $io_id,
									'io_scope_of_work_id' => $scope_id,
									'value' => ''	
								);
								$this->db->insert('io_scope_of_work_ceklist',$ceklist);
							}
							
						}

							
						// AMBIL KEMBALI
						// $io_scope_of_work_ceklist = $this->db->select('a.id,a.value,b.name')
						// 									 ->where('a.io_id',$io_id)
						// 									 ->from('io_scope_of_work_ceklist a')
						// 									 ->join('io_scope_of_work b','a.io_scope_of_work_id = b.id')
						// 									 ->get()->result_object();
						// $ceklist_count = count($io_scope_of_work_ceklist);
					}
				}
				/*END*/ 
				$data['scope_of_work'] = $this->db->select('a.id,a.value,b.attachment,b.name,b.id as scope_id')
													 ->where('a.io_id',$io_id)
													 ->from('io_scope_of_work_ceklist a')
													 ->join('io_scope_of_work b','a.io_scope_of_work_id = b.id')
													 ->get()->result_object();
													 
				$data['scope_of_work_count'] = count($data['scope_of_work']);

				if( $data['scope_of_work_count'] % 2 != 0 ){
					$data['scope_of_work'][] = 'E';
					$data['scope_of_work_count'] += 1;
				}
				//$data['scope_max_table_row'] = ceil($data['scope_of_work_count'] / 2);

			}
				//print_r($data);
				//die();
			    ini_set('memory_limit','32M'); // boost the memory limit if it's low <img src="http://davidsimpson.me/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
			    $html = $this->load->view('pdfs/_'.$tbl[$what], $data, true); // render the view into HTML
			     
			    $this->load->library('pdf');
			    $pdf = $this->pdf->load();
			  
				$pdf->WriteHTML($html);

				$pdf->Output($filename.'.pdf','D'); 
		
			//// PDF ENDED
		}
	}

}